package com.YCH.user.service.Impl;

import com.YCH.common.fastdfs.FastDfsClient;
import com.YCH.model.article.pojos.TbMaterial;
import com.YCH.model.common.dtos.ResponseResult;
import com.YCH.model.common.enums.AppHttpCodeEnum;
import com.YCH.model.mappers.app.TbMaterialMapper;
import com.YCH.model.user.pojos.TbUser;
import com.YCH.model.user.vo.imageInfoVo;
import com.YCH.user.service.MaterialService;
import com.YCH.utils.threadlocal.AppThreadLocalUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;

@Service
@SuppressWarnings("all")
@Slf4j
public class MaterialServiceImpl implements MaterialService {
    @Value("${FILE_SERVER_URL}")
    private String fileServerUrl;

    @Autowired
    private FastDfsClient fastDFSClient;
    @Autowired
    private TbMaterialMapper tbMaterialMapper;

    @Override
    public ResponseResult uploadPicture(MultipartFile multipartFile) {
        TbUser user = AppThreadLocalUtils.getUser();
        if(user == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        if (multipartFile == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        String originFileName = multipartFile.getOriginalFilename();
        String extName = originFileName.substring(originFileName.lastIndexOf(".") + 1);
        if(!extName.matches("(gif|png|jpg|jpeg)")) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_IMAGE_FORMAT_ERROR);
        }
        // StringBuilder imgUrl = new StringBuilder(fileServerUrl);
        String fileId = null;
        //上传图片获得文件id
        try {
            fileId = fastDFSClient.uploadFile(multipartFile.getBytes(), extName);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("user {} upload file {} to fastDFS error, error info:n",user.getId(),originFileName, e.getMessage());
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
        }
        //上传成功保存媒体资源到数据库
        TbMaterial tbMaterial = new TbMaterial();
        tbMaterial.setCreatTime(new Date());
        tbMaterial.setType((short) 0);
        tbMaterial.setUrl(fileId);
        // tbMaterial.setArticleId(user.getId());
        tbMaterial.setAuthorId(user.getId());
        tbMaterial.setIsCollection((short) 0);
        tbMaterialMapper.insert(tbMaterial);
        //设置返回值
        imageInfoVo imageInfo = new imageInfoVo();

        tbMaterial.setUrl(fileServerUrl + tbMaterial.getUrl());
        return ResponseResult.okResult(tbMaterial);
    }
}
